package com.hsd.znsh.utils;

import org.apache.commons.codec.binary.Base64;

import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/*
 * @auther: wangjiacai
 *
 * @create: 2018-06-29 17:52:33
 */
public class RsaDsaEcUtil {


    public static void initKey(String algorithm,RSAPublicKey rsaPublicKey,RSAPrivateKey rsaPrivateKey) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm.toUpperCase());
        keyPairGenerator.initialize(512);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    }

    public static String sign(String algorithm,String signMethod,String content,RSAPrivateKey rsaPrivateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm.toUpperCase());
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Signature signature = Signature.getInstance(signMethod);
        signature.initSign(privateKey);
        signature.update(content.getBytes());
        byte[] res = signature.sign();
        return Base64.encodeBase64String(res);
    }

    public static boolean verify(String algorithm,String signMethod,String publickey,String content,String sign) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm.toUpperCase());
        byte[] encodeKey= Base64.decodeBase64(publickey);
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(encodeKey);
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Signature signature = Signature.getInstance(signMethod);
        signature.initVerify(publicKey);
        signature.update(Base64.decodeBase64(content));
        return signature.verify(Base64.decodeBase64(sign));
    }

}
